<template>
  <div class="month_static">
    <div class="month_select">
      <div class="title item">2022</div>
      <div 
        class="item" 
        :class="{'item_select': selectMonthIndex === index}" 
        @click="handleSelectMonth(new Date().getMonth() + 1 - index, index)"
        v-for="(item, index) in new Date().getMonth() + 1"
        :key="index"
      >{{ handleGetSelectMonth(new Date().getMonth() + 1 - index) }}</div>
    </div>
    <div class="body">
      <div class="money_card">
        <div class="item">
          <div class="text">月支出</div>
          <div class="money">{{ billData.pay.toFixed(2) }}</div>
        </div>
        <div class="item">
          <div class="text">月收入</div>
          <div class="money">{{ billData.income.toFixed(2) }}</div>
        </div>
        <div class="item">
          <div class="text">月结余</div>
          <div class="money">{{ (billData.income - billData.pay).toFixed(2) }}</div>
        </div>
      </div>
      <div class="month_1 month">
        <div class="header">
          <div class="title">收支统计</div>
          <income-pay-button @select="handleSelectMoneyType"></income-pay-button>
        </div>
        <histogram-month class="chart" :x-data="xData" :y-data="yData" ref="histogramMonnth"></histogram-month>
      </div>
      <div class="month_2 month">
        <div class="header">
          <div class="title">资产走势</div>
        </div>
        <line-chart class="chart" :x-data="xData" :y-data="moreData" ref="lineChart"></line-chart>
      </div>
      <div class="month_3 month">
        <div class="header">
          <div class="title" @click="handleSelectPieType">{{ pieTypeIndex === 'pay' ? '支出占比' : '收入占比' }}<i class="iconfont icon-zhihuan"></i></div>
          <div class="button" @click="handleGoBillList">当月账单></div>
        </div>
        <pie-chart :data="pieData" class="chart" ref="pieChart" :title="pieTypeIndex === 'pay' ? '支出占比' : '收入占比'"></pie-chart>
      </div>
      <div class="month_4 month">
        <div class="header">
          <div class="title">支出数据</div>
        </div>
        <list-chart :data="listData"></list-chart>
      </div>
      <div class="month_5 month">
        <div class="header">
          <div class="title">报表统计</div>
        </div>
        <table-chart :data="tableData"></table-chart>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue'
import IncomePayButton from './IncomePayButton.vue'
import HistogramMonth from './HistogramMonth.vue'
import LineChart from './LineChart.vue'
import PieChart from './PieChart.vue'
import ListChart from './ListChart.vue'
import TableChart from './TableChart.vue'
import { getBillListForRange } from '@/api/bill'
import dayjs from 'dayjs'
import { getClassTitle, getMonthCount, getStartAndEnd, handleGetFormatList } from '@/utils/helper'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default defineComponent({
  components: {
    IncomePayButton,
    HistogramMonth,
    LineChart,
    PieChart,
    ListChart,
    TableChart
},
  setup() {
    const monthCount = ref(0)
    const store = useStore()
    const router = useRouter()
    const classList = computed(() => store.state.classList)
    const xData = ref([''])
    const yData = ref([0])
    const moreData = ref([0])
    const pieData = ref([{ value: 1048, name: 'Baidu' }])
    const listData = ref([
      {
        name: '居家生活',
        count: 5,
        icon: 'icon-zhankai',
        money: 570.00,
        proportion: 47.85
      }
    ])
    const tableData = ref([{
        date: '08-04',
        income: 0.00,
        pay: 33.29,
      }])
    const moneyTypeIndex = ref('pay')
    const pieTypeIndex = ref('pay')
    const selectMonthIndex = ref(0)
    const selectMonth = ref(new Date())
    const billData = ref({
      pay: 0,
      income: 0,
      bills: [{
        bills: [],
        pay: 0,
        income: 0,
        date: ''
      }]
    })
    const moneyList = ref([{
      income: 0, 
      pay: 0, 
      date: ''
    }])
    const histogramMonnth = ref()
    const lineChart = ref()
    const pieChart = ref()
    const incomeData = ref([0])
    const pieIncomeData = ref([{value: 0, name: ''}])
    const piePayData = ref([{value: 0, name: ''}])
    const payData = ref([0])
    const mapData = ref(new Map())
    // 清空所有数据
    const handleClearData = () => {
      moneyList.value = []
      incomeData.value = []
      payData.value = []
      mapData.value  = new Map()
      pieIncomeData.value = []
      piePayData.value = []
      billData.value = {
        pay: 0,
        income: 0,
        bills: [{
          bills: [],
          pay: 0,
          income: 0,
          date: ''
        }]
      }
      pieData.value = []
      pieIncomeData.value = []
      yData.value = []
      xData.value = []
      moreData.value = []
      listData.value = []
      tableData.value = []
    }
    // 修改月度账单类型income/pay
    const handleSelectMoneyType = (type: string) => {
      if(moneyTypeIndex.value !== type) {
        moneyTypeIndex.value = type
        yData.value = moneyTypeIndex.value === 'pay' ? payData.value : incomeData.value
        setTimeout(() => {
        histogramMonnth.value.init()
      }, 200)
      }
    }
    // 选择月份
    const handleSelectMonth = (month: number, index: number) => {
      selectMonthIndex.value = index
      const date = getStartAndEnd(new Date(2022, month - 1, 1))
      selectMonth.value = date.start
      monthCount.value = getMonthCount(month, 2022)
      handleClearData()
      getBillData(date.start, date.end)
    }
    // 通过月份的index返回对应格式字符串
    const handleGetSelectMonth = (index: number) => {
      const month = new Date().getMonth() + 1
      if(index === month) {
        return '本月'
      } else if(month - index === 1) {
        return '上月'
      } else {
        return index + '月'
      }
    }
    // 获取当前所选月份账单
    const getBillData = (start: Date, end: Date) => {
      getBillListForRange({
        start: dayjs(start).format('YYYY-MM-DD 00:00:00'),
        end: dayjs(end).format('YYYY-MM-DD 23:59:59'),
        type: 'month'
      }).then((res) => {
        billData.value = {pay: 0, income: 0, bills: []}
        if(typeof res.code === 'number' && res.code === 100) {
          if(res.data) {
            billData.value = res.data[0]
            let data: never[] = []
            billData.value.bills.forEach(item => {
              data.push(...item.bills)
            });
            getListData(data)
            getMonthList(start)
          } else {
            redrawChart()
          }
        }
      })
    }
    // 获取monthList数据
    const getMonthList = (start: Date) => {
      moneyList.value = []
      moneyList.value = handleGetFormatList(billData.value.bills, start, monthCount.value)
      getxyData()
      getTableData()
    }
    // 获取month_1（xData, yData）数据
    const getxyData = () => {
      xData.value = []
      yData.value = []
      moreData.value = []
      incomeData.value = []
      payData.value = []
      for(let i = 0; i < moneyList.value.length; i++) {
        xData.value.push(String(i + 1))
        incomeData.value.push(moneyList.value[i].income)
        payData.value.push(moneyList.value[i].pay)
        moreData.value.push(eval(incomeData.value.join('+'))-eval(payData.value.join('+')))
      }
      yData.value = moneyTypeIndex.value === 'pay' ? payData.value : incomeData.value
      redrawChart()
    }
    // 重绘图表
    const redrawChart = () => {
      setTimeout(() => {
        histogramMonnth.value.init()
        lineChart.value.init()
        pieChart.value.init()
      }, 200)
    }
    // 获取报表数据
    const getTableData = () => {
      tableData.value = []
      billData.value.bills.forEach(item => {
        const { income, pay, date } = item
        const data = { income, pay, date: dayjs(date).format('MM-DD') }
        tableData.value.push(data)
      });
    }
    // 获取列表展示数据
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const getListData = (data: any) => {
      listData.value = []
      mapData.value.clear()
      data.forEach((item: { titleId: number; type: string; money: number, subTitleId: number, icon: string }) => {
        const {money, titleId, type, subTitleId, icon } = item
        mapData.value.set(titleId, {
          money: mapData.value.get(titleId) ? mapData.value.get(titleId).money + money : money,
          count: mapData.value.get(titleId) ? mapData.value.get(titleId).count + 1 : 1,
          name: type === 'pay' ? getClassTitle(false, titleId, classList.value) : getClassTitle(true, subTitleId, classList.value),
          type,
          icon: type === 'pay' ? getClassTitle(false, titleId, classList.value, true) : icon
        })
      })
      console.log(mapData.value, '270');
      mapData.value.forEach((key) => {
        const { type, name, count, money, icon } = key
        if(type === 'pay') {
          const data = { name, count, money, proportion: Number((money*100/billData.value.pay).toFixed(2)), icon }
          listData.value.push(data)
        }
      });
      listData.value.sort((a ,b) => {
        return b.proportion - a.proportion
      })
      getPieData()
    }
    // 获取饼图数据
    const getPieData = () => {
      pieIncomeData.value = []
      piePayData.value = []
      mapData.value.forEach((key) => {
        const { type, money, name } = key
        const data = { value: money, name }
        if(type === 'pay') {
          piePayData.value.push(data)
        } else {
          pieIncomeData.value.push(data)
        }
      });
      pieData.value = pieTypeIndex.value === 'pay' ? piePayData.value : pieIncomeData.value
    }
    // 修改饼图收支类型
    const handleSelectPieType = () => {
      if(pieTypeIndex.value === 'pay') {
        pieTypeIndex.value = 'income'
      } else {
        pieTypeIndex.value = 'pay'
      }
      pieData.value = pieTypeIndex.value === 'pay' ? piePayData.value : pieIncomeData.value
      setTimeout(() => {
        pieChart.value.init()
      }, 200)
    }
    // 跳转到帐单列表页面
    const handleGoBillList = () => {
      router.push({
        path: '/billList',
        query: {
          date: JSON.stringify(selectMonth.value)
        }
      }) 
    }
    onMounted(() => {
      handleSelectMonth(new Date().getMonth() + 1, 0)
    })
    return {
      moneyTypeIndex,
      selectMonthIndex,
      xData,
      yData,
      pieData,
      listData,
      tableData,
      billData,
      histogramMonnth,
      lineChart, 
      moreData,
      pieChart,
      pieTypeIndex,
      handleSelectMoneyType,
      handleSelectMonth,
      handleGetSelectMonth,
      handleSelectPieType,
      handleGoBillList
    }
  }
})
</script>

<style scoped>
  .month_select {
    width: 100%;
    display: flex;
    overflow-x: auto;
    background-color: white;
    padding: 6px 16px;
  }
  .month_select .item {
    padding: 10px 16px;
    min-width: 33px;
  }
  .month_select .item_select {
    color: #F9C3C2;
    position: relative;
  }
  .month_select .item_select::before {
    content: "";
    position: absolute;
    border: 10px solid;
    border-color: transparent transparent #F9C3C2 transparent;
    bottom: -4%;
    left: 32%;
  }
  .money_card {
    background-color: #F9C3C2;
    padding: 10px 30px;
    color: #fff;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
  }
  .money_card .text {
    font-size: 14px;
  }
  .money_card .money {
    font-size: 20px;
  }
  .body {
    margin: 16px 16px 0;
    height: calc(100vh - 200px);
    overflow-y: auto;
  }
  .month {
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    padding: 10px;
  }
  .month .header {
    display: flex;
    justify-content: space-between;
  }
  .chart {
    height: 300px;
    width: 100%;
  }
  .month_3 .button {
    color: #F9C3C2;
  }
</style>
